package com.gjs.bedorder.business;

import java.util.List;
import java.util.Map;

import com.gjs.bedorder.tools.JDBCTools;

public class BedInfo {
	private static String QUERY_ALL_BEDS = "SELECT * FROM bed_info ORDER BY bed_no";
	private static String QUERY_REMAIN_BEDS = "SELECT * FROM bed_info WHERE order_user_id IS NULL";
	private static String ORDER_BED = "UPDATE bed_info SET color = 'red', order_user_id = ?, order_user_name = ? WHERE bed_no = ?";
	private static String QUERY_WHETHER_ORDER = "SELECT * FROM bed_info WHERE (bed_no = ? OR order_user_id = ?) AND color = 'red'";
	private static String QUERY_ORDERED_BED_NO = "SELECT bed_no FROM bed_info WHERE order_user_id = ?";
	private static String CANCEL_ORDER = "UPDATE bed_info SET color = 'white', order_user_id = null WHERE bed_no = ?";
	
	public static List<Map<String, Object>> getAllBeds() {
		return JDBCTools.getObjects(QUERY_ALL_BEDS);
	}
	
	public static List<Map<String, Object>> getRemainBeds() {
		return JDBCTools.getObjects(QUERY_REMAIN_BEDS);
	}
	
	public static void orderBed(String bedNo, String userId, String name) {
		JDBCTools.update(ORDER_BED, userId, name, bedNo);
	}
	
	public static boolean checkOrder(String condition) {
		return JDBCTools.queryHasData(QUERY_WHETHER_ORDER, condition, condition) > 0;
	}
	
	public static String getOrderedBedNo(String userId) {
		if (userId == null) {
			return null;
		}
		return JDBCTools.getValue(QUERY_ORDERED_BED_NO, userId);
	}
	
	public static Map<String, Object> getOrderedBedInfo(List<Map<String, Object>> allbeds, String userId) {
		if (userId == null) {
			return null;
		}
		
		for (Map<String, Object> bed : allbeds) {
			if (userId.equals(bed.get("order_user_id"))) {
				return bed;
			}
		}
		return null;
	}
	
	public static boolean cancelOrder(String bed_no) {
		return JDBCTools.update(CANCEL_ORDER, bed_no) > 0;
	}
}
